/**
 * Created by Administrator on 2015/11/6 0006.
 */

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var wh = require('when');
//var mongoose = require("mongoose");
var logger = require("./utils/logger.js");
var multer = require('multer');
var config = require('./config');
var DB = require('./server/CRUD');
DB = new DB("menu");

var app = express();
logger.use(app);

//var uploadPath = "J:/Resources";
var uploadPath = config.uploadPath;


app.set("views", __dirname + "/jade");
app.set("view engine", "jade");
app.enable("trust proxy");
app.engine("jade", require("jade").__express);

app.use(cookieParser("video"));
app.use(bodyParser.json({limit: '3mb'}));
app.use(multer({dest: uploadPath}));
app.use(bodyParser.urlencoded({extended: true}));

app.use(express.static(path.join(__dirname + "/public")));

require("./handle/User").register(app);
require("./handle/Video").register(app);
require("./handle/Check").register(app);
require("./handle/Menu").register(app);


app.get("/", function(req, res, next) {
    res.redirect('/sign-in');
})

app.use(function (req, res) {
    console.log(req.originalUrl)
    console.log("test");
    res.send(200, "this is handled in app.use().");
});

app.use(function (err, req, res, next) {
    console.log(err);
    res.statius(500).end();
})

app.user = {
    username: "test",
    password: "123"
}

app.locals = {};

//app.appid = "wx033d23e4476b3cfc";
//app.secret = "95cc118b4e8aacb69400d5c0986552cf";
app.appid = config.appid;
app.secret = config.secret;

app.locals.getToken = function () {
    return require('./utils/weixin-token').register(app);
}

app.locals.getTicket = function () {
    return require('./utils/weixin-ticket').register(app);
}

app.locals.getMenu = function () {
    return require('./utils/weixin-menu').register(app);
}

app.getVip = function(){
    var menus = app.locals.menu.button
    for(var b in menus){
        if (menus[b].name == "付费会员"){
            app.locals.vip = {}
            var sb = menus[b]["sub_button"]
            for(var i=0;i<sb.length;i++){
                app.locals.vip[i+1] = sb[i].name
            }
        }
    }
    console.log(app.locals.vip)
    return app.locals.vip
}

app.locals.getMenu().then(function(){

    DB.deleteData({}, function(){ // 删除旧数据
        DB.create(app.locals.menu, function (r) {
        })
    })
})

server = require('http').createServer(app);

var port = 9300;

wh.resolve(server.listen(port)).then(function () {
    logger.logger.info("Server started on " + port);
});